package bc.running.forum.db;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Clob;
import java.text.DateFormat;
import java.util.Date;
import java.util.Formatter;
import java.util.GregorianCalendar;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;

import bc.running.forum.db.translators.ClobDataTranslator;

public abstract class Utils {
	
	public static void writeln(BufferedWriter out,String line) throws IOException {
		out.write(line);
		out.newLine();
	}
	
	public static  String encodeIP(String ip) {
		String[] fragments = ip.split("\\.");
		Formatter formatter = new Formatter();
		formatter = formatter.format("%02x%02x%02x%02x", new Integer(fragments[0]),new Integer(fragments[1]),new Integer(fragments[2]),new Integer(fragments[3]));
		final String result = formatter.toString();
		return result;
	}
	
	public static String xmlEscaping(String data) {
		if (data == null || data.isEmpty()) {
			return data;
		}
		return StringEscapeUtils.escapeXml(data);
	}
	
	public static String zipOutputFolder(final String dbName) throws Exception {
		File outFolder = new File("out");
		if(!outFolder.exists()) {
			throw new RuntimeException("Error while zipping output folder: Output folder does not exists.");
		}
		if(!outFolder.isDirectory()) {
			throw new RuntimeException("Error while zipping output folder: Output folder is not a folder.");
		}
		byte[] buf = new byte[1024];
		final String outFilename = getZipfileName(dbName);
		ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outFilename));
		String[] fileNames = outFolder.list();
		for (String fileName : fileNames) {
			if(!fileName.endsWith(".xml")) {
				continue;
			}
			FileInputStream in = new FileInputStream("out/" + fileName);
	        out.putNextEntry(new ZipEntry(fileName));
	        int len;
	        while ((len = in.read(buf)) > 0) {
	            out.write(buf, 0, len);
	        }
	        out.closeEntry();
	        in.close();
		}
		out.close();
		return outFilename;
	}
	
	private static String getZipfileName(final String dbName) {
		String now = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG).format(new Date());
	    now = now.replaceAll(" ", "_");        
	    now = now.replaceAll(":", "_");
	    now = now.replaceAll(",", "");	    
		final String outFilename = dbName + "_" + now + "_backup.zip";
		return outFilename;
	}
	
	public static int convertDate(String _date) {
		String year = _date.substring(0, 4);
		String month =  _date.substring(4, 6);
		String day = _date.substring( 6, 8);
		String hour = _date.substring( 8, 10);
		String min = _date.substring( 10, 12);
		String sec = _date.substring( 12, 14);
		GregorianCalendar calendar = new GregorianCalendar(new Integer(year),new Integer(month),
														   new Integer(day),new Integer(hour),
														   new Integer(min),new Integer(sec)); 
		return (int) (calendar.getTimeInMillis() /1000);
	}
	
	public static String getStringFromClob(Clob _clob) throws Exception {
		return (String)TRANSLATOR.translate(_clob);
	}
	
	
	private static void findElements(final String tag,final String msg) {
		if(msg == null || msg.isEmpty()) {
			return;
		}
		final String startTag = "<" + tag + " ";
		final String endTag = "/" + tag + ">";
		final int endTagLen = endTag.length();
		int offset = 0;
		String _msg = msg;
		while(true) {
			_msg = _msg.substring(offset,_msg.length());
			int tagStartIndex = StringUtils.indexOfIgnoreCase(_msg,startTag,offset);
			int tagEndIndex = StringUtils.indexOfIgnoreCase(_msg,endTag,offset);
			if(tagStartIndex != -1 && tagEndIndex != -1) {
				String element = _msg.substring(tagStartIndex, tagEndIndex + endTagLen);
				System.out.println(element);
				offset = tagEndIndex + endTagLen;
			} else {
				break;
			}
		}
	}
	
	public static String hrefToBBCode(String msg) {
		findElements("a",msg);
		return "";
	}
	public static String iframeToBBCode(String msg) {
		findElements("iframe",msg);
		return "";
	}
	
	public static String imageToBBCode(String msg) {
		findElements("img",msg);
		return "";
	}
	
	public static void main(String [] args) {
		String str = "<table style=\"width:auto;\"><tr><td><a href=\"http://picasaweb.google.com/lh/photo/DaPqFuLLZwDdDyhIIzj-wg?feat=embedwebsite\"><img src=\"http://lh3.ggpht.com/_NdXZ2S_Z5FQ/SqEcr61ejLI/AAAAAAAABPs/ijEs5YM6IJA/s144/DSC01295.JPG\" /></a></td></tr><tr><td style=\"font-family:arial,sans-serif; font-size:11px; text-align:right\">From <a href=\"http://picasaweb.google.com/amihai.zivan/vCTrFI?feat=embedwebsite\">חלושעס</a></td></tr></table>";
		hrefToBBCode(str);
	}
	
	class AnchorInfo {
		int start;
		int end;
		String anchor;
		String href;
		ImageInfo imageInfo;
		String linkText;
	}
	
	class ImageInfo {
		String src;
		int height;
		int width;
	}

	
	private static  final ClobDataTranslator TRANSLATOR = new ClobDataTranslator();
	public static final String FIELD_TEMPLATE = "<field name=\"%s\">%s</field>";


}
